<template>
  <div class="app-container">
    <div class="grid-content ep-bg-purple" />
    <el-row :gutter="20">
      <el-col :span="8" class="border-right">
        <el-button type="primary" plain @click="handleAdd" class="margin-bottom" v-hasPermi="['coordination:improvement:add']">检查内容上报</el-button>
        <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="68px">
          <el-form-item label="收费站" prop="deptId" v-if="deptId==101">
            <el-tree-select v-model="queryParams.deptId" :data="deptOptions" :props="{ value: 'id', label: 'label', children: 'children' }" value-key="id"
              class="margin-right" placeholder="请选择部门" check-strictly clearable @change="bindChangeTree($event,'deptId')" />
          </el-form-item>
          <el-form-item label="时间" prop="checkDate">
            <el-date-picker clearable v-model="queryParams.checkDate" type="date" value-format="YYYY-MM-DD" placeholder="请选择时间">
            </el-date-picker>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <div class="ul scroll">
          <div class="list" :class="item.id==selectId?'active':''" v-for="(item,index) in offcialList" :key="index" @click.stop="handleCurrentChange(item.id)">
            <div class="flex between">
              <div class="flex flex-sub">
                <div class="serice">{{index+1}}</div>
                <div class="source"><el-tag :type="item.checkType==1?'warning':item.checkType==2?'success':'danger'"><dict-tag :options="check_type"
                      :value="item.checkType" /></el-tag> </div>
                <div class="name">{{item.deptName}}</div>
              </div>

              <div class="flex flex-right">
                <el-button link type="primary" icon="Edit" @click="handleUpdate(item)"   v-if="item.deptId==deptId" v-hasPermi="['coordination:improvement:edit']"></el-button>
                <el-button link type="primary" icon="Delete" @click="handleDelete(item)"   v-if="item.deptId==deptId" v-hasPermi="['coordination:improvement:remove']"></el-button>
                <el-button type="primary" @click="bindRouterCheck(item.sourceDeptId,item.id)" v-hasPermi="['coordination:improvement:exist']"
                  v-if="item.deptId!=deptId&&deptId!=101">自查</el-button>
              </div>
            </div>

            <div class="demand">下发时间：{{ parseTime(item.checkDate, '{y}-{m}-{d}') }}</div>

          </div>
        </div>
        <div v-if="offcialList.length==0"><el-empty></el-empty></div>
      </el-col>
      <el-col :span="16">
        <div class="grid-content ep-bg-purple"></div>
        <el-radio-group v-model="radioType" @change="bindChangeType" class="margin-bottom">
          <el-radio-button label="检查内容" value="1" />
          <el-radio-button label="问题清单" value="2" />
          <el-radio-button label="整改清单" value="3" />
        </el-radio-group>

        <div class="empty-top"></div>
        <el-table v-loading="loading" :data="implementList" show-overflow-tooltip @selection-change="handleSelectionChange" height="610px">
          <el-table-column type="index" width="65" label="序号" align="center" />
          <el-table-column label="类别" align="center" prop="categoryType">
            <template #default="scope">
              <dict-tag :options="check_category" :value=" scope.row.categoryType" />
            </template>
          </el-table-column>
          <el-table-column label="项目" align="center" prop="checkProject" />
          <el-table-column label="检查内容" align="center" prop="checkContent" />
          <el-table-column label="通过/不通过" align="center" prop="isPass" width="180" v-if="radioType!='检查内容'">
            <template #default="scope">
              <span>{{ scope.row.isPass==1?'通过':'不通过' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="不通过原因" align="center" prop="reason" v-if="radioType!='检查内容'" />

          <el-table-column label="是否已完成整改" align="center" prop="isRectify" width="140" v-if="radioType=='整改清单'">
            <template #default="scope">
              <span>{{ scope.row.isRectify=="1"?'是':'否' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="整改措施" align="center" prop="correctiveMeasures" v-if="radioType=='整改清单'" />
          <el-table-column label="整改时限" align="center" prop="rectificationTime" v-if="radioType=='整改清单'" />

          <el-table-column label="操作" align="center" prop="" v-if="radioType=='检查内容'">
            <template #default="scope">
              <el-button link type="primary" icon="Edit" @click="handleUpdateList(scope.row,scope.$index)"
                v-hasPermi="['coordination:improvement:edit']">修改</el-button>
              <el-button link type="primary" icon="Delete" @click="handleDeleteList(scope.row,scope.$index)"
                v-hasPermi="['coordination:improvement:remove']">删除</el-button>
            </template> </el-table-column>

          <el-table-column label="操作" align="center" prop="" v-if="radioType=='整改清单'">
            <template #default="scope">
              <el-button type="danger" @click="bindShowRectification(scope.row.id,scope.$index)" v-hasPermi="['coordination:detail:edit']">整改</el-button>
            </template> </el-table-column>
        </el-table>

      </el-col>
    </el-row>
    <el-dialog :title="title" v-model="openOverDialog" width="800px" append-to-body>
      <el-form ref="overRef" :model="formOver" :rules="rules" label-width="120px">
        <el-form-item label="是否已完成整改" prop="isRectify">
          <el-radio-group style="width:100%" v-model="formOver.isRectify" @change="bindChangePass">
            <el-radio v-for="dict in overList" :key="dict.value" :label="dict.value" :value="dict.value" size="large">{{dict.label}}</el-radio>

          </el-radio-group>
        </el-form-item>
        <el-form-item label="整改措施" prop="correctiveMeasures">
          <el-input v-model="formOver.correctiveMeasures" type="textarea" placeholder="请输入" />
        </el-form-item>

        <el-form-item label="整改时限" prop="rectificationTime">
          <el-date-picker style="width:100%" clearable v-model="formOver.rectificationTime" type="date" value-format="YYYY-MM-DD" placeholder="请选择">
          </el-date-picker>
        </el-form-item>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFormOver">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 添加或修改重点工作管理对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body>
      <el-form ref="offcialRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="收费站" prop="deptId">
          <el-tree-select v-model="form.deptId" :data="deptOptions" :props="{ value: 'id', label: 'label', children: 'children' }" value-key="id"
            :disabled="true" class="margin-right" placeholder="请选择部门" check-strictly clearable @change="bindChangeTree($event,'deptId')" style="width:100%" />
        </el-form-item>
        <el-form-item label="检查类型" prop="checkType">
          <el-select v-model="form.checkType" :disabled="true" style="width:100%">
            <el-option v-for="dict in check_type" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>

        </el-form-item>
        <el-form-item label="检查时间" prop="checkDate">
          <el-date-picker style="width:100%" clearable v-model="form.checkDate" type="date" value-format="YYYY-MM-DD" placeholder="请选择">
          </el-date-picker>
        </el-form-item>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 添加或修改重点工作管理对话框 -->

    <!-- 添加或修改整改信息对话框 -->
    <el-dialog title="修改检查内容" v-model="opendialog" width="800px" append-to-body>
      <el-form ref="improvementRef" :model="formList" :rules="rules" label-width="120px">
        <el-form-item label="类别" prop="categoryType">
          <el-select style="width:100%" v-model="formList.categoryType">
            <el-option v-for="dict in check_category" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="项目" prop="checkProject">
          <el-input v-model="formList.checkProject" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="检查内容" prop="checkContent">
          <el-input v-model="formList.checkContent" type="textarea" placeholder="请输入" rows="6" />
        </el-form-item>
        <el-form-item label="检查结果" prop="isPass">
          <el-select style="width:100%" v-model="formList.isPass" @change="bindChangePass">
            <el-option v-for="dict in possList" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="不通过原因" prop="reason" v-if="isReason">
          <el-input v-model="formList.reason" type="textarea" placeholder="请输入" rows="6" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="bindProjectSubmit">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <Viewer ref="fileViewerRef" :dialog-doc="dialogDoc" />
  </div>
</template>
  
  <script setup name="Major">
import { listImprovement, getImprovement, isExist, updateImprovement, delImprovement, getImprovementRight, updateImprovementRight, delImprovementRight, getImprovementLeft } from "@/api/coordination/improvement";
import { deptTreeSelect } from "@/api/system/user";
const { proxy } = getCurrentInstance();
const { check_type, check_category } = proxy.useDict('check_type', 'check_category');
import Viewer from "@/components/Custom/viewer.vue";
import { getCKInfo } from '@/utils/auth'

const baseUrl = import.meta.env.VITE_APP_BASE_API;
const router = useRouter();
const offcialList = ref([]);
const fileViewerRef = ref()
const tbCooOfficialImplList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const checkedTbCooOfficialImpl = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const daterangeSendTime = ref([]);
const implementList = ref([])
const selectId = ref()
const deptOptions = ref([])
const radioDept = ref("全部收费站")
const deptIds = ref([])
const dialogDoc = ref(false)
const radioType = ref('检查内容')
const deptId = ref(Number(getCKInfo('deptId')))
const details = ref()
const possList = ref([{ label: "通过", value: "1" }, { label: "不通过", value: "0" }])
const overList = ref([{ label: "完成", value: "1" }, { label: "未完成", value: "0" }])
const opendialog = ref(false)
const openOverDialog = ref(false)
const data = reactive({
  form: {},
  formList: {},
  formOver: {},
  queryParams: {
    checkDate:"",
    deptId:""
  },
  rules: {
  }
});

const { queryParams, form, rules, formList, formOver } = toRefs(data);

/** 查询重点工作管理列表 */
function getList() {
  loading.value = true;
  // queryParams.value.params = {};

  listImprovement(queryParams.value).then(response => {
    offcialList.value = response.data;
    // total.value = response.total;
    loading.value = false;


  });
}

const bindChangeType = (val) => {

  if (val == '问题清单') {
    implementList.value = details.value?.problem
  } else if (val == '整改清单') {
    implementList.value = details.value?.problem
  } else {
    implementList.value = details.value.content
  }
}

/** 查询落实管理列表 */
function getImplementList() {
  if (!selectId.value) return;
  loading.value = true;
  implementList.value = []
  getImprovement(selectId.value).then(response => {
    details.value = response.data;


    if (radioType.value == '检查内容') {
      implementList.value = response.data.content;
    } else {
      implementList.value = response.data.problem
    }

    loading.value = false;

  });
}
/** 查询部门下拉树结构 */
function getDeptTree() {
  deptTreeSelect().then(response => {
    deptOptions.value = response.data;
  });
}
// 取消按钮
function cancel() {
  open.value = false;
  opendialog.value = false;
  reset();
}

const handleCurrentChange = (id) => {
  selectId.value = id;
  radioType.value = "检查内容"
  getImplementList();
}

// 表单重置
function reset() {
  form.value = {
    id: null,

  };
  tbCooOfficialImplList.value = [];
  proxy.resetForm("offcialRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  // queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  daterangeSendTime.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  router.push({ path: "/coordination/improvement", query: { type: 1 } })

}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getImprovementLeft(_id).then(response => {
    form.value = response.data;
    // tbCooOfficialImplList.value = response.data.tbCooOfficialImplList;
    open.value = true;
    title.value = "修改整改提升";
    // getImplementList()
  });
}

/** 修改按钮操作 */
function handleUpdateList(row, index) {
  reset();
  const _id = row.id || ids.value
  getImprovementRight(_id).then(response => {
    formList.value = response.data.content[index];
    opendialog.value = true;
    // getImplementList();
    // title.value = "修改检车内筒";
  });
}

/** 删除列表按钮操作 */
function handleDeleteList(row) {
  const _ids = row.detailId || ids.value;
  proxy.$modal.confirm('是否确认删除检查内容管理编号为"' + _ids + '"的数据项？').then(function () {
    return delImprovementRight(_ids);
  }).then(() => {
    getImplementList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["offcialRef"].validate(valid => {
    if (valid) {
      updateImprovement(form.value).then(response => {
        proxy.$modal.msgSuccess("保存成功");
        open.value = false;
        getList()
      });
    }
  });
}


/** 提交按钮 整改*/
function submitFormOver() {
  proxy.$refs["overRef"].validate(valid => {
    if (valid) {
      updateImprovementRight(formOver.value).then(response => {
        proxy.$modal.msgSuccess("保存成功");
        openOverDialog.value = false;
        getImplementList()
      });
    }
  });
}


/** 提交按钮 */
function bindProjectSubmit() {
  proxy.$refs["improvementRef"].validate(valid => {
    if (valid) {
      updateImprovementRight(formList.value).then(response => {
        proxy.$modal.msgSuccess("保存成功");
        opendialog.value = false;
        getImplementList()
      });
    }
  });
}


/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除整改管理编号为"' + _ids + '"的数据项？').then(function () {
    return delImprovement(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}

/** 重点工作落实情况上报序号 */
function rowTbCooOfficialImplIndex({ row, rowIndex }) {
  row.index = rowIndex + 1;
}

/** 重点工作落实情况上报添加按钮操作 */
function handleAddTbCooOfficialImpl() {
  let obj = {};
  obj.deptId = "";
  obj.implType = "";
  obj.implDescribe = "";
  obj.proof = "";
  obj.certifier = "";
  obj.status = "";
  tbCooOfficialImplList.value.push(obj);
}

/** 重点工作落实情况上报删除按钮操作 */
function handleDeleteTbCooOfficialImpl() {
  if (checkedTbCooOfficialImpl.value.length == 0) {
    proxy.$modal.msgError("请先选择要删除的重点工作落实情况上报数据");
  } else {
    const tbCooOfficialImpls = tbCooOfficialImplList.value;
    const checkedTbCooOfficialImpls = checkedTbCooOfficialImpl.value;
    tbCooOfficialImplList.value = tbCooOfficialImpls.filter(function (item) {
      return checkedTbCooOfficialImpls.indexOf(item.index) == -1
    });
  }
}

/** 复选框选中数据 */
function handleTbCooOfficialImplSelectionChange(selection) {
  checkedTbCooOfficialImpl.value = selection.map(item => item.index)
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('/coordination/major/export', {
    ...queryParams.value
  }, `整改_${new Date().getTime()}.xlsx`)
}
const bindRouterCheck = (sourceDeptId, id) => {
  isExist({ deptId: deptId.value, sourceDeptId: id }).then(res => {
    if (res.data) {
      router.push({ path: "/coordination/improvement", query: { type: 2, id, deptId: id } })
    } else {
      proxy.$modal.msgError("该数据已经自查过");
    }
  })

}

function deepClone(obj) {
  let objClone = Array.isArray(obj) ? [] : {}
  if (obj && typeof obj === 'object') {
    for (var key in obj) {
      if (obj.hasOwnProperty(key)) {
        // 判断ojb子元素是否为对象，如果是，递归复制
        if (obj[key] && typeof obj[key] === 'object') {
          objClone[key] = deepClone(obj[key])
        } else {
          // 如果不是，简单复制
          objClone[key] = obj[key]
        }
      }
    }
  }
  return objClone
}

const bindShowRectification = (id, index) => {
  openOverDialog.value = true;
  formOver.value = deepClone(implementList.value[index])

}
// 预览
const previewFun = (file) => {
  dialogDoc.value = true;
  let data = {};
  // 上传过的文件组成完成的网络路径
  if (file && file.indexOf(',') == -1) {
    data.src = `${baseUrl}${file}`;
  } else if (file && file.indexOf(',') != -1) {
    let src = file.split(',');
    let srcArr = []
    src.forEach(item => { srcArr.push(`${baseUrl}${item}`) })
    data.src = srcArr.join(',');
    file = srcArr[0]
  }

  const arr = file.split(".");
  const suffix = arr[arr.length - 1];
  if (suffix == "docx" || suffix == "doc") {
    fileViewerRef.value?.viewDocx(data, '重点工作');
  } else if (suffix == "xlsx" || suffix == "xls") {
    fileViewerRef.value?.viewXlsx(data);
  } else if (suffix == "jpg" || suffix == "jpeg" || suffix == "png") {
    fileViewerRef.value?.viewImg(data);
  } else if (suffix == "pdf") {
    fileViewerRef.value?.viewPdf(data);
  }
};

getList()
getDeptTree()
  </script>
  
  <style scoped>
.margin-bottom {
  margin-bottom: 10px;
}
.list {
  margin: 10px;
  cursor: pointer;
  padding: 15px;
  box-sizing: border-box;
  border: 1px solid #f5f5f5;
  box-shadow: 0 0 5px #f5f5f5;
  position: relative;
  border-radius: 10px;
  border: 1px solid #fff;
}
.list .flex {
  display: flex;
  align-items: center;
}
.between {
  justify-content: space-between;
  margin-bottom: 6px;
}
.list .serice {
  width: 20px;
  line-height: 20px;
  background: #246bcc;
  color: #fff;
  border-radius: 4px;
  text-align: center;
  font-size: 12px;
  margin-right: 6px;
}
.list .name {
  max-width: 400px;
  flex-shrink: 0;
  color: #246bcc;
  font-size: 16px;
  font-weight: 600;
  text-overflow: ellipsis;
  overflow: hidden;
  white-space: nowrap;
}
.list .demand {
  font-size: 14px;
  color: #999;
  padding-left: 32px;
  line-height: 1.6;
  margin-top: 6px;
}
.list .time {
  font-size: 12px;
  color: #c7c7c7;
  line-height: 1.6;
  padding-left: 32px;
}
.list .text-theme {
  color: #246bcc;
  font-size: 30px;
}
.list .source {
  font-size: 16px;
  color: #333;
  margin-right: 6px;
}
.list .absolute {
  position: absolute;
  right: 20px;
  top: 45px;
  font-size: 22px;
  font-weight: 600;
  color: #999;
}
.empty-top {
  height: 10px;
}
.list.active {
  background: #e2eeff;
  border: 1px solid #246bcc;
}
.flex-right {
  width: 60px;
  flex-shrink: 0;
}
.flex-sub {
  flex: 1;
}
.ul {
  height: 600px;
  overflow-y: auto;
}
.title {
  font-size: 20px;
  font-weight: 600;
}
.border-right {
  border-right: 1px solid #dddddd;
}
</style>
  